package com.cl.controller;

import com.alibaba.fastjson.JSON;
import com.cl.service.impl.UserServiceImpl;
import com.cl.utils.CodeUtil;
import com.cl.utils.MsgUtil;
import com.cl.utils.SendMailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class RegisterController {
    @Autowired
    private CodeUtil codeUtil;
    @Autowired
    private SendMailUtil sendMailUtil;
    @Autowired
    private MsgUtil msgUtil;
    @Autowired
    private UserServiceImpl userService;
    @PostMapping("/code")
    public String getCode(HttpServletRequest request, @RequestParam("email")String email){
        String code = codeUtil.getCode();
        HttpSession session = request.getSession();
        session.setAttribute("code",code);
        sendMailUtil.sendSimpleMail("验证码",code,email);
        return JSON.toJSONString(msgUtil.success("请到邮箱查看验证码"));
    }
    @PostMapping("/register")
    public String register(@RequestParam("email")String email,@RequestParam("pwd")String pwd,@RequestParam("code")String code,HttpServletRequest request){
        HttpSession session = request.getSession();
        String s = code.toUpperCase();
        String sessionCode = (String) session.getAttribute("code");
        if (!sessionCode.equals(s)){
            return JSON.toJSONString(msgUtil.fail("验证码错误"));
        }
        if (userService.queryByEmail(email)!=null){
           return JSON.toJSONString(msgUtil.fail("邮箱已注册"));
        }
        userService.register(email,pwd);
        return JSON.toJSONString(msgUtil.success("注册成功"));
    }
}
